<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
/**
 * 委外加工单
 *
 * @icon fa fa-circle-o
 */
class Outsourcing extends Backend
{

    /**
     * Procedure模型对象
     * @var \app\admin\model\kuyou\Outsourcing
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuyou\Outsourcing;
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $stores_list = Db::name('kuyou_stores')->where(['status'=>'1'])->select();
        $this->view->assign("storesList", $stores_list);
        $this->assignconfig("storesList", $stores_list);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['customers_id'] = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->column('customer_name');
                $production_id = Db::name('kuyou_plan')->where(['purchase_code'=>$list_v['plan_code']])->value('id');
                $goods_list = Db::name('kuyou_plan_info')->where(['plan_id'=>$production_id])->field('goods_name,number')->select();
                $str = '';
                foreach ($goods_list as $goods_list_k=>$goods_list_v){
                    $str .= $goods_list_v['goods_name'].'*'.$goods_list_v['number'].' ';
                }
                $list[$list_k]['goods_info'] = $str;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('ids',$ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('Please fill in the detailed data'));
                }

                $set= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
                $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');
                $data = [];
                $number = 0;$all_money = 0;
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        $all_money += (float)$params['all_money'][$k];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v])->field('id,goods_name,serial,batch,auxiliary')->find();
                        if(!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])){
                            $this->error(__('Please choose').$goods['goods_name'].__('Warehouse'));
                        }
                        $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$params['batch_id'][$k]])->find();

                        if($goods['auxiliary']==1 && empty($params['goods_attr'][$k])){
                            $this->error(__('Please choose').$goods['goods_name'].__('attribute'));
                        }

                        if($goods['batch']==1 && $batch==1){
                            if(empty($params['batch'][$k])){
                                $this->error(__('Please choose').$goods['goods_name'].__('Production Batch'));
                            }
                            if(empty($batch_data)){
                                $this->error($goods['goods_name'].__('Production batch does not exist'));
                            }
                        }

                        $serial_code = [];
                        if(isset($params['period_period'][$k]) && $goods['serial']==1 && $set==1){
                            if(empty($params['period_period'][$k])){
                                $this->error(__('Please enter').$goods['goods_name'].__('Product serial number'));
                            }
                            $period_period = unserialize($params['period_period'][$k]);
                            foreach ($period_period as $period_period_k=>$period_period_v){
                                $serial_code[] = $period_period_v['serial'];
                            }
                            $where = [];
                            $where['serial'] = ['in',$serial_code];
                            if(!empty($params['purchase_id'][$k])){
                                $where['purchase_code'] = $params['purchase_id'][$k];
                            }
                            $goods_serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');
                            if(empty($goods_serial)){
                                $this->error($goods['goods_name'].__('The product serial number does not exist'));
                            }
                            foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                if(!in_array($serial_code_v,$goods_serial)){
                                    $this->error($serial_code_v.__('The product serial number does not exist'));
                                }
                            }
                            $goods_serials = Db::name('kuyou_goods_serial')->where(['store_status'=>['in',[0,2]],'serial'=>['in',$serial_code]])->column('serial');
                            if(!empty($goods_serials)){
                                $goods_serials = implode(',',$goods_serials);
                                $this->error(__('Product serial number').$goods_serials.'已经待出库，不可重复出库');
                            }
                        }

                        $data[] = [
                            'type'          =>  2,
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $v,
                            'goods_name'    =>  $goods['goods_name'],
                            'goods_note'    =>  $params['goods_note'][$k],
                            'unit_id'       =>  (float)$params['goods_unit'][$k],
                            'default_unit'  =>  (float)$params['default_unit'][$k],
                            'purchase'      =>  (float)$params['unit_price'][$k],
                            'number'        =>  (float)$params['number'][$k],
                            'basic_nmber'   =>  (float)$params['basic_nmber'][$k],
                            'money'         =>  (float)$params['all_money'][$k],
                            'stores_id'     =>  (float)$params['stores_id'][$k],
                            'allow_stock'   =>  (float)$params['allow_stock'][$k],
                            'stock_number'  =>  0,
                            'need_number'   =>  (float)$params['all_money'][$k],
                            'goods_attr'    =>  (float)$params['goods_attr'][$k],
                            'remark'        =>  $params['remark'][$k],
                            'batch_id'      => isset($batch_data['id'])?$batch_data['id']:null,
                            'batch_name'    => isset($batch_data['batch_name'])?$batch_data['batch_name']:null,
                            'manufacture'   => !empty($params['manufacture'][$k])?strtotime($params['manufacture'][$k]):null,
                            'guarantee'     => !empty($params['guarantee'][$k])?$params['guarantee'][$k]:null,
                            'validity'      => !empty(strtotime($params['validity'][$k]))?strtotime($params['validity'][$k]):null,
                            'period'        =>  $params['period_period'][$k]===''?null:$params['period_period'][$k],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }

                $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$params['plan_code']])->find();
                if(empty($plan)){
                    $this->error(__('Production plan query failed'));
                }
                if(empty($data)){
                    $this->error(__('Please fill in the detailed data'));
                }else{
                    $admin = Session::get('admin');
                    if(isset($plan['id'])){
                        unset($plan['id']);
                    }
                    $row = $plan;
                    $row['plan_code'] = $params['plan_code'];
                    $row['purchase_code'] = $params['purchase_code'];
                    $row['purchase_time'] = strtotime($params['purchase_time']);
                    $row['work_time'] = strtotime($params['work_time']);
                    $row['finish_time'] = strtotime($params['finish_time']);
                    $row['remark'] = $params['note'];
                    $row['work_id'] = $params['work_id'];
                    $row['number'] = $number;
                    $row['all_money'] = $all_money;
                    $row['free_money'] = (float)$params['free_money'];
                    $row['customers_id'] = (float)$params['customers_id'];
                    $row['examine_status'] = '0';
                    $row['createtime'] = time();
                    $row['updatetime'] = time();
                    $row['preparation_id'] = $admin['id'];
                    $row['operation_id'] = $admin['id'];
                    if($this->model->where(['purchase_code'=>trim($params['purchase_code'])])->find()){
                        $this->error(__('The document number is already occupied'));
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    if(!empty($row)){
                        $result = $this->model->insertGetId($row);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['production_id'] = $result;
                    }
                    Db::name('kuyou_outsourcing_info')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($examine!=1){
                        try {
                            $exa = $this->examine($result,1);
                        } catch (Exception $e) {
                        }
                        if(!isset($exa) || $exa['status']!=1){
                            $exa = $this->examine($result,1);
                            try {
                                $this->del($result);
                            } catch (Exception $e) {
                            }
                            $this->error($exa['msg']);
                        }
                    }
                    $this->success(__('Added successfully'));
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $code = (new Goods())->getCodes('',35);
        $this->view->assign("code", $code);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
                if($row['examine_status']==1 && $examine==1){
                    $this->error(__('Cannot edit approved data'));
                }
                $purchase_id = Db::name('kuyou_material')->where(['outsourcing_code'=>$row['purchase_code']])->column('id');
                if(!empty($purchase_id)){
                    $this->error(__('Cannot edit data for generated return orders'));
                }
                $purchase_id = Db::name('kuyou_acceptance')->where(['outsourcing_code'=>$row['purchase_code']])->column('id');
                if(!empty($purchase_id)){
                    $this->error(__('Cannot edit data of generated acceptance forms'));
                }

                $params = $this->preExcludeFields($params);
                $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if(!isset($status)){
                    $this->error(__('Please fill in the detailed data'));
                }

                $set= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
                $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');
                $data = [];
                $number = 0;$all_money = 0;
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        $all_money += (float)$params['all_money'][$k];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v])->field('id,goods_name,serial,batch,auxiliary')->find();
                        if(!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])){
                            $this->error(__('Please choose').$goods['goods_name'].__('Warehouse'));
                        }
                        if($goods['auxiliary']==1 && empty($params['goods_attr'][$k])){
                            $this->error(__('Please choose').$goods['goods_name'].__('attribute'));
                        }
                        $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$params['batch_id'][$k]])->find();
                        if($goods['batch']==1 && $batch==1){
                            if(empty($params['batch'][$k])){
                                $this->error(__('Please choose').$goods['goods_name'].__('Production Batch'));
                            }
                            if(empty($batch_data)){
                                $this->error($goods['goods_name'].__('Production batch does not exist'));
                            }
                        }

                        $serial_code = [];
                        if(isset($params['period_period'][$k]) && $goods['serial']==1 && $set==1){
                            if(empty($params['period_period'][$k])){
                                $this->error(__('Please enter').$goods['goods_name'].__('Product serial number'));
                            }
                            $period_period = unserialize($params['period_period'][$k]);
                            foreach ($period_period as $period_period_k=>$period_period_v){
                                $serial_code[] = $period_period_v['serial'];
                            }
                            $where = [];
                            $where['serial'] = ['in',$serial_code];
                            if(!empty($params['purchase_id'][$k])){
                                $where['purchase_code'] = $params['purchase_id'][$k];
                            }
                            $goods_serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');
                            if(empty($goods_serial)){
                                $this->error($goods['goods_name'].__('The product serial number does not exist'));
                            }
                            foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                if(!in_array($serial_code_v,$goods_serial)){
                                    $this->error($serial_code_v.__('The product serial number does not exist'));
                                }
                            }
                            $goods_serials = Db::name('kuyou_goods_serial')->where(['store_status'=>['in',[0,2]],'serial'=>['in',$serial_code]])->column('serial');
                            if(!empty($goods_serials)){
                                $goods_serials = implode(',',$goods_serials);
                                $this->error(__('Product serial number').$goods_serials.'已经待出库，不可重复出库');
                            }
                        }

                        $data[] = [
                            'type'          =>  2,
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $v,
                            'goods_name'    =>  $goods['goods_name'],
                            'goods_note'    =>  $params['goods_note'][$k],
                            'unit_id'       =>  (float)$params['goods_unit'][$k],
                            'default_unit'  =>  (float)$params['default_unit'][$k],
                            'purchase'      =>  (float)$params['unit_price'][$k],
                            'number'        =>  (float)$params['number'][$k],
                            'basic_nmber'   =>  (float)$params['basic_nmber'][$k],
                            'money'         =>  (float)$params['all_money'][$k],
                            'stores_id'     =>  (float)$params['stores_id'][$k],
                            'allow_stock'   =>  (float)$params['allow_stock'][$k],
                            'stock_number'  =>  0,
                            'need_number'   =>  (float)$params['all_money'][$k],
                            'goods_attr'    =>  (float)$params['goods_attr'][$k],
                            'remark'        =>  $params['remark'][$k],
                            'batch_id'      => isset($batch_data['id'])?$batch_data['id']:null,
                            'batch_name'    => isset($batch_data['batch_name'])?$batch_data['batch_name']:null,
                            'manufacture'   => !empty($params['manufacture'][$k])?strtotime($params['manufacture'][$k]):null,
                            'guarantee'     => !empty($params['guarantee'][$k])?$params['guarantee'][$k]:null,
                            'validity'      => !empty(strtotime($params['validity'][$k]))?strtotime($params['validity'][$k]):null,
                            'period'        =>  $params['period_period'][$k]===''?null:$params['period_period'][$k],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }

                $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$params['plan_code']])->find();
                if(empty($plan)){
                    $this->error(__('Production plan query failed'));
                }
                if(empty($data)){
                    $this->error(__('Please fill in the detailed data'));
                }else{
                    $admin = Session::get('admin');
                    if(isset($plan['id'])){
                        unset($plan['id']);
                    }
                    $rowdata = $plan;
                    $rowdata['plan_code'] = $params['plan_code'];
                    $rowdata['purchase_code'] = $params['purchase_code'];
                    $rowdata['purchase_time'] = strtotime($params['purchase_time']);
                    $rowdata['work_time'] = strtotime($params['work_time']);
                    $rowdata['finish_time'] = strtotime($params['finish_time']);
                    $rowdata['remark'] = $params['note'];
                    $rowdata['work_id'] = $params['work_id'];
                    $rowdata['free_money'] = (float)$params['free_money'];
                    $rowdata['customers_id'] = (float)$params['customers_id'];
                    $rowdata['number'] = $number;
                    $rowdata['examine_status'] = '0';
                    $rowdata['all_money'] = $all_money;
                    $rowdata['updatetime'] = time();
                    $rowdata['preparation_id'] = $admin['id'];
                    $rowdata['operation_id'] = $admin['id'];
                    if($this->model->where(['purchase_code'=>trim($params['purchase_code']),'id'=>['<>',$ids]])->find()){
                        $this->error(__('The document number is already occupied'));
                    }
                }


                $result = false;
                Db::startTrans();
                try {
                    if($examine!=1 && $row['examine_status']==1){
                        $this->examine($ids,2);
                    }

                    if(!empty($rowdata)){
                        $result = $this->model->where(['id'=>$row['id']])->update($rowdata);
                    }

                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['production_id'] = $row['id'];
                    }
                    Db::name('kuyou_outsourcing_info')->where(['production_id'=>$row['id']])->delete();
                    Db::name('kuyou_outsourcing_info')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($examine!=1){
                        try {
                            $exa = $this->examine($ids,1);
                        } catch (Exception $e) {
                        }
                        if(!isset($exa) || $exa['status']!=1){
                            $this->error(__('No rows were inserted'));
                        }
                    }
                    $this->success(__('Edited successfully'));
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $purchase_info = Db::name('kuyou_outsourcing_info')->where(['production_id'=>$row['id']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purchase_info[$purchase_info_k]['unit'] = json_decode((new GoodsPurchase())->getUnit($purchase_info_v['goods_code']),true);
        }
        $this->view->assign("purchase_info", $purchase_info);

        $this->view->assign("row", $row);

        //审核禁止输入
        $examine_set= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if($examine_set==1 && $row['examine_status']==1){
            $this->assign('exclass','hiddens');
        }
        $this->assignconfig("examine_status", $row['examine_status']);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            foreach ($list as $k=>$row){
                $purchase_id = Db::name('kuyou_material')->where(['outsourcing_code'=>$row['purchase_code']])->column('id');
                if(!empty($purchase_id)){
                    $this->error(__('Cannot manipulate data of generated return orders'));
                }
                $purchase_id = Db::name('kuyou_acceptance')->where(['outsourcing_code'=>$row['purchase_code']])->column('id');
                if(!empty($purchase_id)){
                    $this->error(__('Cannot manipulate the data of the generated acceptance form'));
                }
            }

            $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {

                    if($v['examine_status']==1 && $examine==1){
                        exception(__('Cannot delete audited data'));return;
                    }elseif ($v['examine_status']==1 && $examine!=1){
                        try {
                            $this->examine($v['id'],2);
                        } catch (Exception $e) {
                        }
                    }

                    $count += $v->delete();
                    Db::name('kuyou_outsourcing_info')->where(['production_id'=>$v['id']])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //审核/反审核
    public function examine($ids = null,$examine=1){
        $examine_set= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if(empty($ids)){
            if($examine_set!=1){
                return ['status'=>0,'msg'=>__('System error')];
            }
            $this->error(__('Please select the data to be operated on'));
        }
        $admin = Session::get('admin');
        if($examine==1){
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
            $production_id = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->column('id');


            $purchase_info_id = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->column('id');
            $info_list = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->select();

            $editstock = [];
            $goods_stock = [];
            $purchase_info = [];
            $goods_stock_log = [];//收发详情
            $serial_log = [];//序列号跟踪
            $serial_data = [];
            foreach ($info_list as $list_k=>$list_v){
                $picking = Db::name('kuyou_outsourcing')->where(['id'=>$list_v['production_id']])->find();
                if(!empty($list_v['period'])){
                    $goods_serial = unserialize($list_v['period']);
                    foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                        $this_serial = Db::name('kuyou_goods_serial')->where(['serial'=>$goods_serial_v['serial']])->find();
                        if(empty($this_serial)){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>__('serial number').$goods_serial_v['serial'].__('non-existent')];
                            }
                            $this->error(__('serial number').$goods_serial_v['serial'].__('non-existent'));
                        }
                        $serial_data[] = [
                            'id'=>$this_serial['id'],
                            'sale_id' => $picking['id'],
                            'sale_code' => $picking['purchase_code'],
                            'status' => '3',
                            'store_status' => '2',
                            'old_status' => $this_serial['status'],
                            'old_store' => $this_serial['store_status'],
                        ];
                        $serial_log[] = [
                            'goods_id'=>$list_v['goods_id'],
                            'stores_id'=>$list_v['stores_id'],
                            'attribute_id'=>$list_v['goods_attr'],
                            'serial'=>$goods_serial_v['serial'],
                            'business_type'=>'20',
                            'store_status'=>'2',
                            'remarks' => $list_v['remark'],
                            'purchase_id'=>$list_v['id'],
                            'customer_id'=>null,
                            'purchase_code'=>$picking['purchase_code'],
                            'purchase_time' => $picking['purchase_time'],
                            'createtime'  => time(),
                            'updatetime'  => time(),
                        ];
                    }
                }

                $info_list[$list_k]['sales_order_id']    = $list_v['id'];
                $info_list[$list_k]['createtime']        = time();
                $info_list[$list_k]['updatetime']        = time();
                $stock_number = $list_v['basic_nmber'];
                $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id,goods_name')->find();
                $status = false;
                foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                    if($goods_stock_v['id']==$goods['id']){
                        $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']-$stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $goods_stock[] = [
                        'id'=>$goods['id'],
                        'inventory'=>$goods['inventory']-$stock_number,
                    ];
                }
                //商品库存
                $where = [];
                $where['goods_code'] = $list_v['goods_code'];
                $where['stores_id'] = $list_v['stores_id'];
                if($list_v['goods_attr']>0){
                    $goods_attr = $list_v['goods_attr'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                }

                //获取成本单价
                $balance_cost=0;$balance_unit=0;
                $goodsInfo = json_decode((new GoodsPurchase())->getUnit($list_v['goods_code'],$list_v['stores_id'],$list_v['goods_attr']),true);
                $unitData = isset($goodsInfo['unit'])?$goodsInfo['unit']:[];
                if(empty($unitData)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>__('Product information retrieval error')];
                    }
                    $this->error(__('Product information retrieval error'));
                }else{
                    foreach ($unitData as $unitData_k=>$unitData_v){
                        if($unitData_v['id']==$goods['unit_id']){
                            $balance_unit = $unitData_v['purchase'];
                        }
                    }
                }
                //获取成本单价结束

                $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id')->find();
                if($stock){
                    $status = false;
                    foreach ($editstock as $editstock_k=>$editstock_v){
                        if($editstock_v['id']==$stock['id']){
                            $editstock[$editstock_k]['stock'] -= $stock_number;
                            $status = true;
                            $balance_cost   = (round($balance_unit*$stock_number,4));
                        }
                    }
                    if(!$status){
                        $editstock[] = [
                            'id'=>$stock['id'],
                            'stock'=>(round($stock['stock']-$stock_number,4))
                        ];
                        $balance_cost   = (round($balance_unit*$stock_number,4));
                    }
                }else{
                    $store = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                    if($examine!=1){
                        if($examine_set!=1){
                            return ['status'=>0,'msg'=>$goods['goods_name'].'库存不足,操作失败'];
                        }
                        return ['status'=>0,'msg'=>$goods['goods_name'].'库存不足,操作失败'];
                    }
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>__('commodity').$goods['goods_name'].$store.__('Insufficient inventory')];
                    }
                    $this->error(__('commodity').$goods['goods_name'].$store.__('Insufficient inventory'));
                }
                $purchase_info[] = $list_v['id'];

                //收发详情
                if($goods){
                    $goods_stock_log[] = (new Goods())->setDataInfo([
                        'purchase_code' => $picking['purchase_code'],
                        'purchase_id'   => $list_v['id'],
                        'purchase_time' => $picking['purchase_time'],
                        'business_type' => '20',
                        'customer_id'   => null,
                        'goods_id'      => $goods['id'],
                        'goods_code'    => $list_v['goods_code'],
                        'attribute_id'  => (float)$list_v['goods_attr'],
                        'goods_unit'    => (float)$list_v['unit_id'],
                        'stores_id'     => (float)$list_v['stores_id'],
                        'remark'        => $list_v['remark'],
                        'out_number'    => (float)$list_v['number'],
                        'out_basics'    => (float)$list_v['basic_nmber'],
                        'out_unit'      => $balance_unit,
                        'out_cost'      => $balance_cost,
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ]);
                }
                //收发详情结束
            }
            foreach ($editstock as $editstock_k=>$editstock_v){
                if($editstock_v['stock']<0){
                    $store = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>$goods['goods_name'].'库存不足,操作失败'];
                    }
                    $this->error($store.'库存不足,操作失败');
                }
            }

            //批次库存数据
            //获取设置
            $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $number_decimal = $setList['number_decimal']['value'];
            $goods_serial = Db::name('kuyou_outsourcing_info')->where(['id'=>['in',$purchase_info_id]])->select();

            $goods_batch_add = [];$goods_batch_edit = [];$goods_batch_log = [];$goods_batch_info=[];
            foreach ($goods_serial as $k=>$v){
                $goods = Db::name('kuyou_goods')->where((new Goods())->setWhere(['goods_code'=>$v['goods_code']]))->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
                if($goods['batch']==1){
                    //先通过单位计算需修改多单位商品的库存数量
                    if($goods['unit_id']==$v['unit_id']){
                        $stock_number = $v['number'];
                    }else{
                        $unit_conversion = Db::name('kuyou_unit_conversion')->where((new Goods())->setWhere(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']]))->value('advance_rate');
                        if(empty($unit_conversion)){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>__('Failed to query product unit information')];
                            }
                            $this->error(__('Failed to query product unit information'));
                        }else{
                            $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                        }
                    }

                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    if($v['goods_attr']){
                        $where['attribute_id'] = $v['goods_attr'];
                    }
                    $where['stores_id'] = $v['stores_id'];
                    $where['batch_id'] = $v['batch_id'];
                    $where = (new Goods())->setWhere($where);
                    $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                    if(empty($goods_batch_stock)){
                        $status = false;
                        foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                            if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$v['goods_id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                                $goods_batch_add[$goods_batch_add_k]['stock'] -= $stock_number;
                                $status = true;
                            }
                        }
                        if(!$status){
                            $goods_batch_add[] = (new Goods())->setDataInfo([
                                'batch_id' => $v['batch_id'],
                                'goods_id' => $goods['id'],
                                'goods_code' => $v['goods_code'],
                                'attribute_id' => $v['goods_attr'],
                                'stores_id' => $v['stores_id'],
                                'stock' => $stock_number,
                                'createtime' => time(),
                                'updatetime' => time(),
                            ]);
                        }
                    }else{
                        if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                            $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                        }else{
                            $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                        }
                    }
                    foreach ($goods_batch_edit as $k2=>$v2){
                        if($v2<0){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>__('commodity').$goods['goods_name'].__('Insufficient inventory')];
                            }
                            $this->error(__('commodity').$goods['goods_name'].__('Insufficient inventory'));
                        }
                    }

                    //商品批次跟踪
                    $goods_batch_log[] = (new Goods())->setDataInfo([
                        'goods_id'      => $goods['id'],
                        'goods_unit'    => $v['unit_id'],
                        'stores_id'     => $v['stores_id'],
                        'batch_id'      => (float)$v['batch_id'],
                        'number'        => (float)$v['number'],
                        'purchase_code' => $picking['purchase_code'],
                        'purchase_time' => $picking['purchase_time'],
                        'business_type' => '20',
                        'remarks'       => $v['remark'],
                        'order_id'      => $v['id'],
                        'unit_price'    => $v['purchase'],
                        'all_money'     => $v['money'],
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ]);

                    $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['batch_id']])->find();
                    if(empty($batch_data)){
                        $this->error(__('commodity').$goods['goods_name'].__('Batch query failed'));
                    }
                    $goods_batch_info[] = [
                        'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                        'goods_id'    => $goods['id'],
                        'goods_code'  => $v['goods_code'],
                        'attribute_id'=> $v['goods_attr'],
                        'goods_unit'  => $v['unit_id'],
                        'stores_id'   => $v['stores_id'],
                        'stock'       => (float)$v['number'],
                        'number'      => (float)$v['number'],
                        'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                        'manufacture' => $batch_data['manufacture'],
                        'guarantee'   => $batch_data['guarantee'],
                        'validity'    => $batch_data['validity'],
                        'type'        => 7,
                        'purchase_id'  => $v['production_id'],
                        'purchase_info_id'   => $v['id'],
                        'createtime'  => time(),
                        'updatetime'  => time(),
                    ];
                }
                //商品批次跟踪结束
            }
            //批次库存数据结束

            Db::startTrans();
            try {

                //序列号跟踪
                if(!empty($serial_log)){
                    Db::name('kuyou_goods_serial_log')->insertAll($serial_log);
                }
                if(!empty($goods_stock_log)){
                    Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                }
                //批次库存数据
                if(!empty($goods_batch_log)){
                    Db::name('kuyou_goods_batch_log')->insertAll($goods_batch_log);
                }
                if(!empty($goods_batch_add)){
                    Db::name('kuyou_goods_batch_stock')->insertAll($goods_batch_add);
                }
                if(!empty($goods_batch_edit)){
                    foreach ($goods_batch_edit as $k=>$v){
                        Db::name('kuyou_goods_batch_stock')->where((new Goods())->setWhere(['id'=>$k]))->update(['stock'=>$v]);
                    }
                }
                //批次库存数据结束

                if(!empty($serial_data)){
                    (new \app\admin\model\kuyou\GoodsSerial())->saveAll($serial_data);
                }
                if(!empty($goods_batch_info)){
                    Db::name('kuyou_goods_batch_sale_info')->insertAll($goods_batch_info);
                }
                if(!empty($editstock)){
                    (new \app\admin\model\kuyou\GoodsStock())->saveAll($editstock);
                }
                if(!empty($goods_stock)){
                    (new \app\admin\model\kuyou\Goods())->saveAll($goods_stock);
                }

                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])
                    ->update(['examine_status'=>1,'examine_id'=>$admin['id'],'examine_time'=>time(),'operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>__('Operation successful')];
                }
                $this->success(sizeof($list).__('The data review was successful'));
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Audit failed'));
            }
        }else{
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->select();
            $production_id = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->column('id');

            foreach ($list as $list_k=>$list_v){
                $order = Db::name('kuyou_material')->where(['outsourcing_code'=>$list_v['purchase_code']])->column('id');
                if(!empty($order)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>__('Cannot manipulate data of generated return orders')];
                    }
                    $this->error(__('Cannot reverse audit data of generated return orders'));
                }
                $order = Db::name('kuyou_acceptance')->where(['outsourcing_code'=>$list_v['purchase_code']])->column('id');
                if(!empty($order)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>__('Cannot manipulate the data of the generated acceptance form')];
                    }
                    $this->error(__('Cannot reverse audit the data of the generated acceptance form'));
                }
            }

            $purchase_info_id = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->column('id');
            $info_list = Db::name('kuyou_outsourcing_info')->where(['production_id'=>['in',$production_id]])->select();

            $editstock = [];
            $goods_stock = [];
            $purchase_info = [];
            $serial_data = [];
            foreach ($info_list as $list_k=>$list_v){
                $picking = Db::name('kuyou_outsourcing')->where(['id'=>$list_v['production_id']])->find();
                if(!empty($list_v['period'])){
                    $goods_serial = unserialize($list_v['period']);
                    foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                        $this_serial = Db::name('kuyou_goods_serial')->where(['serial'=>$goods_serial_v['serial']])->find();
                        if(empty($this_serial)){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>__('serial number').$goods_serial_v['serial'].__('non-existent')];
                            }
                            $this->error(__('serial number').$goods_serial_v['serial'].__('non-existent'));
                        }
                        $serial_data[] = [
                            'id'=>$this_serial['id'],
                            'sale_id' => $picking['id'],
                            'sale_code' => $picking['purchase_code'],
                            'status' => $this_serial['old_status'],
                            'store_status' => $this_serial['old_store'],
                        ];
                    }
                }

                $info_list[$list_k]['sales_order_id']    = $list_v['id'];
                $info_list[$list_k]['createtime']        = time();
                $info_list[$list_k]['updatetime']        = time();
                $stock_number = $list_v['basic_nmber'];
                $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id,goods_name')->find();
                $status = false;
                foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                    if($goods_stock_v['id']==$goods['id']){
                        $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']+$stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $goods_stock[] = [
                        'id'=>$goods['id'],
                        'inventory'=>$goods['inventory']+$stock_number,
                    ];
                }
                //商品库存
                $where = [];
                $where['goods_code'] = $list_v['goods_code'];
                $where['stores_id'] = $list_v['stores_id'];
                if($list_v['goods_attr']>0){
                    $goods_attr = $list_v['goods_attr'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                }

                $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id')->find();
                if($stock){
                    $status = false;
                    foreach ($editstock as $editstock_k=>$editstock_v){
                        if($editstock_v['id']==$stock['id']){
                            $editstock[$editstock_k]['stock'] += $stock_number;
                            $status = true;
                        }
                    }
                    if(!$status){
                        $editstock[] = [
                            'id'=>$stock['id'],
                            'stock'=>(round($stock['stock']+$stock_number,4))
                        ];
                    }
                }else{
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>'库存数据错误，操作失败'];
                    }
                    $this->error('库存数据错误,反审核失败');
                }
                $purchase_info[] = $list_v['id'];
            }

            //批次库存数据
            //获取设置
            $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $number_decimal = $setList['number_decimal']['value'];
            $goods_serial = Db::name('kuyou_outsourcing_info')->where(['id'=>['in',$purchase_info_id]])->select();

            $goods_batch_add = [];$goods_batch_edit = [];
            foreach ($goods_serial as $k=>$v){
                $goods = Db::name('kuyou_goods')->where((new Goods())->setWhere(['goods_code'=>$v['goods_code']]))->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
                if($goods['batch']==1){
                    //先通过单位计算需修改多单位商品的库存数量
                    if($goods['unit_id']==$v['goods_unit']){
                        $stock_number = $v['number'];
                    }else{
                        $unit_conversion = Db::name('kuyou_unit_conversion')->where((new Goods())->setWhere(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']]))->value('advance_rate');
                        if(empty($unit_conversion)){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>__('Failed to query product unit information')];
                            }
                            $this->error(__('Failed to query product unit information'));
                        }else{
                            $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                        }
                    }

                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    if($v['goods_attr']){
                        $where['attribute_id'] = $v['goods_attr'];
                    }
                    $where['stores_id'] = $v['stores_id'];
                    $where['batch_id'] = $v['batch_id'];
                    $where = (new Goods())->setWhere($where);
                    $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                    if(empty($goods_batch_stock)){
                        $status = false;
                        foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                            if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$goods['id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                                $goods_batch_add[$goods_batch_add_k]['stock'] += $stock_number;
                                $status = true;
                            }
                        }
                        if(!$status){
                            $goods_batch_add[] = (new Goods())->setDataInfo([
                                'batch_id' => $v['batch_id'],
                                'goods_id' => $goods['id'],
                                'goods_code' => $v['goods_code'],
                                'attribute_id' => $v['goods_attr'],
                                'stores_id' => $v['stores_id'],
                                'stock' => $stock_number,
                                'createtime' => time(),
                                'updatetime' => time(),
                            ]);
                        }
                    }else{
                        if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                            $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                        }else{
                            $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                        }
                    }
                }
            }
            //批次库存数据结束

            $admin = Session::get('admin');
            Db::startTrans();
            try {
                //序列号跟踪
                if(!empty($purchase_info_id)){
                    Db::name('kuyou_goods_serial_log')->where((new Goods())->setWhere(['business_type'=>'20','purchase_id'=>['in',$purchase_info_id]]))->delete();
                }
                //批次库存数据
                //删除批次跟踪
                if(!empty($purchase_info_id)){
                    Db::name('kuyou_goods_batch_log')->where((new Goods())->setWhere(['business_type'=>'20','order_id'=>['in',$purchase_info_id]]))->delete();
                }
                if(!empty($goods_batch_edit)){
                    foreach ($goods_batch_edit as $k=>$v){
                        Db::name('kuyou_goods_batch_stock')->where((new Goods())->setWhere(['id'=>$k]))->update(['stock'=>$v]);
                    }
                }
                //批次库存数据结束
                if(!empty($serial_data)){
                    (new \app\admin\model\kuyou\GoodsSerial())->saveAll($serial_data);
                }
                if(!empty($purchase_info_id)){
                    Db::name('kuyou_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->delete();
                    Db::name('kuyou_goods_log')->where(['business_type'=>'20','purchase_id'=>['in',$purchase_info_id]])->delete();
                }
                if(!empty($editstock)){
                    (new \app\admin\model\kuyou\GoodsStock())->saveAll($editstock);
                }
                if(!empty($goods_stock)){
                    (new \app\admin\model\kuyou\Goods())->saveAll($goods_stock);
                }
                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])
                    ->update(['examine_status'=>'0','examine_id'=>0,'examine_time'=>'','operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>__('Operation successful')];
                }
                $this->success(sizeof($list).__('The data has been successfully de audited'));
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Anti audit failed'));
            }
        }
    }

    public function choselist(){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $data = input();
            if(isset($data['purchase_code'])){
                $detail = Db::name('kuyou_outsourcing')->where(['purchase_code'=>$data['purchase_code']])->find();
                if($detail){
                    $info = Db::name('kuyou_outsourcing_info')->where(['production_id'=>$detail['id']])->select();
                    foreach ($info as $info_k=>$info_v){
                        $info[$info_k]['unit'] = Db::name('kuyou_unit')->where(['id'=>$info_v['unit_id']])->find();
                    }
                }else{
                    $info = [];
                }
                $result = array("total" => sizeof($info), "rows" => $info);
                return json($result);
            }else{
                list($where, $sort, $order, $offset, $limit) = $this->buildparams();

                $list = $this->model
                    ->where($where)
                    ->where(['examine_status'=>'1'])
                    ->order($sort, $order)
                    ->paginate($limit);

                foreach ($list as $list_k=>$list_v){
                    $list[$list_k]['customers_id'] = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->column('customer_name');
                    $production_id = Db::name('kuyou_plan')->where(['purchase_code'=>$list_v['plan_code']])->value('id');
                    $goods_list = Db::name('kuyou_plan_info')->where(['plan_id'=>$production_id])->field('goods_name,number')->select();
                    $str = '';
                    foreach ($goods_list as $goods_list_k=>$goods_list_v){
                        $str .= $goods_list_v['goods_name'].'*'.$goods_list_v['number'].' ';
                    }
                    $list[$list_k]['goods_info'] = $str;
                }

                $result = array("total" => $list->total(), "rows" => $list->items());
                return json($result);
            }
        }
        return $this->view->fetch();
    }

    public function planinfo(){
        $params = input();
        $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$params['purchase_code']])->find();
        if($plan){
            $info = Db::name('kuyou_plan_info')->where(['plan_id'=>$plan['id']])->select();
            $data = [];
            foreach ($info as $info_k=>$info_v){
                $bom = Db::name('kuyou_bom')->where(['goods_code'=>$info_v['goods_code']])->column('id');
                $info_id = Db::name('kuyou_bom_info')->where(['bom_id'=>['in',$bom]])->select();
                foreach ($info_id as $info_id_k=>$info_id_v){
                    $info_id_v['number'] = $info_id_v['number']*$info_v['number'];
                    $info_id_v['basic_nmber'] = $info_id_v['basic_nmber']*$info_v['number'];
                    $info_id_v['money'] = $info_id_v['money']*$info_v['number'];
                    $data[] = $info_id_v;
                }
            }
            $result = array("total" => sizeof($data), "rows" => $data);
            return json($result);
        }else{
            $this->error(__('Query failed'));
        }
    }
}
